
#include "Nodes.h"

using namespace std;
using namespace ttg_internal;
using namespace ttg::strings;

//---------------------
//--- AttributeNode ---
//---------------------

AttributeNode::AttributeNode(const char *name, const char *value)
{
	this->name = createCopy(name);
	this->value = createCopy(value);
}

const char *AttributeNode::getName() const
{
	return name;
}

const char *AttributeNode::getValue() const
{
	return value;
}

AttributeNode::~AttributeNode()
{
	delete[] value;
	delete[] name;
}

//-------------------
//--- SectionNode ---
//-------------------

SectionNode::SectionNode(const char *name, SectionNode *parent)
{
	this->name = createCopy(name);
	attrit = attrnodes.begin();
	sectionit = sectionnodes.begin();
	this->parent = parent;
}

const char *SectionNode::getName() const
{
	return name;
}

void SectionNode::addAttr(AttributeNode *attrnode)
{
	attrnodes.push_back(const_cast<AttributeNode * const> (attrnode));
	attrit = attrnodes.begin();
}

void SectionNode::addSection(SectionNode *sectionnode)
{
	sectionnodes.push_back(const_cast<SectionNode * const> (sectionnode));
	sectionit = sectionnodes.begin();
}

void SectionNode::resetIterators()
{
	this->attrit = this->attrnodes.begin();
	this->sectionit = this->sectionnodes.begin();
}

const AttributeNode *SectionNode::getAttribute(const char *name)
{
	while (attrit != attrnodes.end())
	{
		if (!strcmp((*attrit)->getName(), name))
		{
			return *(attrit++);
		}
		attrit++;
	}
	return NULL;
}

SectionNode *SectionNode::getSection(const char *name)
{
	while (sectionit != sectionnodes.end())
	{
		if (!strcmp((*sectionit)->getName(), name))
		{
			return *(sectionit++);
		}
		sectionit++;
	}
	return NULL;
}

list<AttributeNode *> &SectionNode::getAttributes()
{
	return attrnodes;
}

list<SectionNode *> &SectionNode::getSections()
{
	return sectionnodes;
}

const AttributeNode *SectionNode::getNextAttribute()
{
	if (attrit != attrnodes.end())
	{
		return *(attrit++);
	}
	return NULL;
}

SectionNode *SectionNode::getNextSection()
{
	if (sectionit != sectionnodes.end())
	{
		return *(sectionit++);
	}
	return NULL;
}

SectionNode *SectionNode::getParent()
{
	return parent;
}

SectionNode::~SectionNode()
{
	delete[] name;
	list <AttributeNode *>::iterator it1 = attrnodes.begin();
	while (it1 != attrnodes.end())
		delete *(it1++);
	list <SectionNode *>::iterator it2 = sectionnodes.begin();
	while (it2 != sectionnodes.end())
		delete *(it2++);
}
